<?php

namespace UserModule\service;

use Config\MysqlLocal;
use UserModule\m\UserOrm;

/**
 * 用户登陆操作
 * Class UserLogin
 * @package UserModule\service
 */
class UserLogin
{
    /**
     * @var UserOrm
     */
    static private $userInfo;

    /**
     * 手机登陆
     * @param $phone
     * @param $password
     * @return bool
     */
    public function loginByPhonePassword($phone, $password)
    {
        $db = MysqlLocal::getDB();
        $result = $db->get(
            UserOrm::USER_TABLE_NAME,
            "*",
            ['phone' => $phone, 'password' => $password]
        );
        if (0 == intval($result['uid']))
            return false;

        // 保存全局登陆信息
        $m = new UserOrm();
        $m->initData($result);
        self::login($m);
        $_SESSION['uid'] = $m->uid;
        return true;
    }

    /**
     * 通过 sessoin 初始化登陆信息
     * @return bool
     */
    public static function initLoginBySession()
    {
        $db = MysqlLocal::getDB();
        $result = $db->get(
            UserOrm::USER_TABLE_NAME,
            "*",
            ['uid' => intval($_SESSION['uid'])]
        );
        if (0 == intval($result['uid']))
            return false;

        // 保存全局登陆信息
        $m = new UserOrm();
        $m->initData($result);
        self::login($m);
        return true;
    }

    /**
     * 登陆操作 保存全局单例用户信息
     * @param $info UserOrm
     * @return bool
     */
    public static function login($info)
    {
        // 已经登陆过
        if (null != self::$userInfo) {
            return false;
        }
        self::$userInfo = $info;
        return true;
    }

    /**
     * 退出登陆
     */
    public static function logout()
    {
        $_SESSION = array();
    }

    /**
     * 登陆用户id
     * @return UserOrm
     */
    public static function loginId()
    {
        return self::$userInfo->uid;
    }

    /**
     * 检查是否登陆
     * @return bool
     */
    public static function checkLogin()
    {
        if (null == $_SESSION['uid']) return false;

        if (null == self::$userInfo) {
            self::initLoginBySession();
        }
        return true;
    }
}